package com.zhilianbao.leyaogo.ui.fragment.me.setting;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bql.commonrow.CommonListRow;
import com.bql.utils.EventManager;
import com.bql.utils.ManifestUtils;
import com.bql.utils.StringUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.constants.SettingConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.model.response.me.NewAppVersionResponse;
import com.zhilianbao.leyaogo.ui.activity.me.setting.AboutUsActivity;
import com.zhilianbao.leyaogo.ui.activity.me.setting.AccountSafeActivity;
import com.zhilianbao.leyaogo.ui.activity.me.setting.IdeaBackActivity;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseFragment;
import com.zhilianbao.leyaogo.utils.DataCleanManager;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Description: 设置 Fragment<br>
 * Author: liu <br>
 */
public class SettingFragment extends BaseFragment {

    @BindView(R.id.idea_back)
    CommonListRow mIdeaBack;
    @BindView(R.id.about_us)
    CommonListRow mAboutUs;
    @BindView(R.id.account_safe)
    CommonListRow mAccountSafe;
    @BindView(R.id.row_setting_new_mes)
    SwitchCompat mRowSettingNewMes;
    @BindView(R.id.row_setting_wifi_auto_play)
    SwitchCompat mRowSettingWifiAutoPlay;
    @BindView(R.id.row_setting_clear_cache)
    CommonListRow mRowSettingClearCache;
    @BindView(R.id.row_setting_new_version)
    CommonListRow mRowSettingNewVersion;
    @BindView(R.id.out_login)
    TextView mOutLogin;
    private String clearCache;
    private String newVersion;
    private String ideaBack;
    private String aboutUs;
    private String accountSafe;
    private boolean isMesNotity;
    private boolean isWifiAutoPlay;
    private static final int REQ_CODE_INSTALL = 200;
    private static final int MSG_WHAT_NET_ERROR = 300;
    private static final int MSG_WHAT_UPDATE_VIEW = 400;
    private boolean mIsUserLogin;
    private CommonDialog mOutLoginDialog;
    private TextView mContent;
    private ProgressDialog mPd;

    public static SettingFragment getInstance() {
        SettingFragment fragment = new SettingFragment();
        return fragment;
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.settings));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        setData();
    }

    /**
     * 初始化数据
     */
    private void setData() {
        clearCache = StringUtils.isEmpty(DataCleanManager.getTotalCacheSize(mActivity), "0M");
        newVersion = StringUtils.isEmpty("", "");
        ideaBack = StringUtils.isEmpty("", "");
        aboutUs = StringUtils.isEmpty("", "");
        accountSafe = StringUtils.isEmpty("", "");
        mRowSettingClearCache.setStatusText(clearCache);
        mRowSettingClearCache.setStatusTextSize(13);
        //        mRowSettingClearCache.getImageRight().setVisibility(View.GONE);
        mRowSettingNewVersion.setStatusText(newVersion);
        mRowSettingNewVersion.setStatusTextSize(13);
        mIdeaBack.setStatusText(ideaBack);
        mAboutUs.setStatusText(aboutUs);
        mAccountSafe.setStatusText(accountSafe);
        mIsUserLogin = Utils.justIsUserLogin();
        if (mIsUserLogin) {
            mOutLogin.setVisibility(View.VISIBLE);
        } else {
            mOutLogin.setVisibility(View.GONE);
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_settings;
    }

    @OnClick({R.id.idea_back, R.id.about_us, R.id.account_safe, R.id.row_setting_clear_cache, R.id.row_setting_new_version, R.id.row_setting_new_mes, R.id.out_login, R.id.row_setting_wifi_auto_play})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.idea_back://意见反馈
                if (mIsUserLogin) {
                    Utils.startActivity(mActivity, IdeaBackActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.about_us://关于我们
                Utils.startActivity(mActivity, AboutUsActivity.class);
                break;
            case R.id.account_safe://账户与安全
                if (mIsUserLogin) {
                    Utils.startActivity(mActivity, AccountSafeActivity.class);
                } else {
                    Utils.gotoLogin();
                }
                break;
            case R.id.row_setting_clear_cache://清除缓存
                cleanCache();
                break;
            case R.id.row_setting_new_version://新版检测
                loadServerVersion();
                break;
            case R.id.row_setting_new_mes://新消息提醒
                // 获取消息提醒的状态取反
                isMesNotity = !isMesNotity;
                //保存状态
                LeYaoGoApplication.getDataKeeper().put(SettingConfig.MES_NOTIFY, isMesNotity);
                break;
            case R.id.row_setting_wifi_auto_play://WiFi下自动播放
                // 获取WiFi下自动播放的状态取反
                isWifiAutoPlay = !isWifiAutoPlay;
                //保存状态
                LeYaoGoApplication.getDataKeeper().put(SettingConfig.WIFI_AUTO_PLAY, isWifiAutoPlay);
                break;
            case R.id.out_login://退出登录
                showOutLoginDialog();
                break;
        }
    }

    /**
     * 退出登录提示框
     */
    private void showOutLoginDialog() {
        if (mOutLoginDialog == null) {
            mOutLoginDialog = CommonDialog.createTwoButton(getString(R.string.confirm), getString(R.string.cancel), getString(R.string.sure_to_login_out));
        }
        mOutLoginDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                mOutLoginDialog.dismiss();
                mActivity.finish();
                Utils.clear();
//                Utils.unregisterPush();
                LeXiuInitService.getInstance().onLegoLogout();
                LeYaoGoApplication.HAS_GOT_SHOPPING_CART_NUM = false;
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_OUT_LOGIN));
            }

            @Override
            public void right() {
                mOutLoginDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mOutLoginDialog.show(getFragmentManager(), "out_login");
    }

    @Override
    public void onStart() {
        super.onStart();
        // 获取消息提醒的状态
        isMesNotity = LeYaoGoApplication.getDataKeeper().get(SettingConfig.MES_NOTIFY, true);
        setStateShow(mRowSettingNewMes, isMesNotity);
        //获取WiFi下自动播放视频的状态
        isWifiAutoPlay = LeYaoGoApplication.getDataKeeper().get(SettingConfig.WIFI_AUTO_PLAY, true);
        setStateShow(mRowSettingWifiAutoPlay, isWifiAutoPlay);
    }

    private void setStateShow(SwitchCompat switchCompat, boolean isOpen) {
        if (isOpen) {//状态开
            switchCompat.setChecked(true);
        } else {//状态关
            switchCompat.setChecked(false);
        }
    }

    private void cleanCache() {
        XToastUtils.showShortToast("清除缓存成功");
        DataCleanManager.clearAllCache(mActivity);
        clearCache = StringUtils.isEmpty(DataCleanManager.getTotalCacheSize(mActivity), "0M");
        mRowSettingClearCache.setStatusText(clearCache);
    }

    public void loadServerVersion() {
        AccountApi.getLastAppVersion(mActivity, 0, 0, new JsonCallback<NewAppVersionResponse>(mActivity) {
            @Override
            public void onSuccess(NewAppVersionResponse newAppVersionResponse, Call call, Response response) {
                getServerVersion(newAppVersionResponse);
            }
        });
    }

    // 获取服务器返回版本号中的数字字符串
    public void getServerVersion(NewAppVersionResponse newAppVersionResponse) {
        if (newAppVersionResponse == null) {
            XToastUtils.showShortToast("当前为最新版本");
            return;
        }
        String appVersion = newAppVersionResponse.getAppVersion();
        String version = null;
        char[] number = appVersion.toCharArray();
        String res = "";
        for (int i = 0; i < number.length; i++) {
            if (("0123456789.").indexOf(number[i] + "") != -1) {
                res += number[i];
                version = res;
            }
        }
        String newVersion = version.substring(0, version.length() - 1);
        try {
            if (newVersion.compareTo(ManifestUtils.getVersionName(mActivity)) > 0) {
                //需要更新
                alertUpdateDialog(newAppVersionResponse);
            } else {
                XToastUtils.showShortToast("当前为最新版本");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 弹出更新的提示框
    protected void alertUpdateDialog(NewAppVersionResponse newAppVersionResponse) {
        View view = View.inflate(mActivity, R.layout.update_dialog, null);
        AlertDialog dialog = Utils.showCornerDialog(mActivity, view, 255, 335);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        TextView updateTitle = (TextView) dialog.findViewById(R.id.update_title);
        TextView updateContent = (TextView) dialog.findViewById(R.id.update_content);
        TextView updateNow = (TextView) dialog.findViewById(R.id.update_now);
        TextView updateLate = (TextView) dialog.findViewById(R.id.update_late);
        updateNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 下载的进度条
                mPd = new ProgressDialog(mActivity, R.style.Dialog_FS);
                View view = View.inflate(mActivity, R.layout.dialog_title, null);
                mContent = (TextView) view.findViewById(R.id.tv_dialog_content);
                mPd.setCustomTitle(view);
                mPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mPd.setProgressNumberFormat(null);
                mPd.setProgressPercentFormat(null);
                mPd.setProgressDrawable(getResources().getDrawable(R.drawable.progress_horizontal));
                mPd.setCancelable(false);
                mPd.setCanceledOnTouchOutside(false);
                Window dialogWindow = mPd.getWindow();
                WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
                p.height = Utils.dp2px(140);
                p.width = Utils.dp2px(270);
                dialogWindow.setAttributes(p);
                mPd.show();
                dialog.dismiss();
                new Thread(new DownloadRunnable(mPd, newAppVersionResponse)).start();
            }
        });
        updateLate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                mRowSettingNewVersion.setStatusText("当前版本" + ManifestUtils.getVersionName(mActivity));
                mRowSettingNewVersion.setStatusText("");
                dialog.dismiss();
            }
        });

    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mContent.setText("正在下载新版本" + msg.arg1 + "%");
            switch (msg.what) {
                case MSG_WHAT_NET_ERROR:
                    XToastUtils.showShortToast("网络连接失败");
                    mPd.dismiss();
                    break;

            }
        }
    };

    // 下载的Runnable
    private class DownloadRunnable implements Runnable {
        private final NewAppVersionResponse mNewAppVersionResponse;
        private ProgressDialog pd;

        public DownloadRunnable(ProgressDialog pd, NewAppVersionResponse newAppVersionResponse) {
            this.pd = pd;
            mNewAppVersionResponse = newAppVersionResponse;
        }

        @Override
        public void run() {
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                String downloadURL = HttpConfig.URL_CLOUD_DOWN + mNewAppVersionResponse.getDownloadUrl();
                URL url = new URL(downloadURL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 连接超时
                conn.setConnectTimeout(5 * 1000);
                // 读取数据超时
                conn.setReadTimeout(5 * 1000);
                // 连接
                conn.connect();
                // 连接成功
                if (conn.getResponseCode() == 200) {
                    // 文件的长度
                    int max = conn.getContentLength();
                    // 设置进度条的最大值
                    pd.setMax(max);
                    // 下载的文件
                    File file = new File(Environment.getExternalStorageDirectory(), mNewAppVersionResponse.getAppName());
                    // 文件的写出流
                    fos = new FileOutputStream(file);
                    is = conn.getInputStream();
                    int len;
                    byte[] buffer = new byte[1024];
                    int progress = 0;
                    while ((len = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        // 当前的进度
                        progress += len;
                        pd.setProgress(progress);
                        int nowProgress = progress * 100 / max;
                        Message message = handler.obtainMessage();
                        message.arg1 = nowProgress;
                        handler.sendMessage(message);
                    }
                    // 安装
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setDataAndType(Uri.parse("file:" + file.getAbsolutePath()), "application/vnd.android.package-archive");
                    // requestCode :请求码,代表是谁发起的请求
                    startActivityForResult(intent, REQ_CODE_INSTALL);
                } else {
                    handler.sendEmptyMessage(MSG_WHAT_NET_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                handler.sendEmptyMessage(MSG_WHAT_NET_ERROR);
            } finally {
                // 关流
                try {
                    if (is != null)
                        is.close();
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQ_CODE_INSTALL:
                if (resultCode == Activity.RESULT_CANCELED) {
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SWITCH_TO_HOME));
                    mActivity.finish();
                }
                break;
        }
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_LOGIN_SUCCESS:
                setData();
                break;
            case LeEventCode.MSG_CODE_SWICH_TO_ME://设置密码成功未登录,回到我的页面
                mActivity.finish();
                break;
        }
    }
}
